package cn.mymall.util;

import cn.mymall.support.ResultCode;
import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.BucketAuthorization;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileBucketLocalAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import cn.ucloud.ufile.http.HttpClient;
import cn.ucloud.ufile.util.JLog;
import cn.ucloud.ufile.util.MimeTypeUtil;
import cn.ucloud.ufile.util.StorageType;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class UCloudFileUploadUtil {
    public static final String PUBLIC_KEY = "TOKEN_2ff4a180-2be0-468b-b020-9bd2d19076a6";
    public static final String PRIVATE_KEY = "a2f6c559-65a2-4e56-8913-b9da44c57b83";
    public static final String BUCKET = "file-res";
    public static final String DOMAIN = "http://file-res.cn-sh2.ufileos.com/";
    private static ObjectConfig config = new ObjectConfig("cn-sh2", "ufileos.com");
    private static final String ROOT_DIR = "siji";

    static {
        /**
         * 开启Debug级别日志
         */
        JLog.SHOW_DEBUG = false;

        /**
         * 配置UfileClient，必须在使用UfileClient之前调用
         */
        UfileClient.configure(new UfileClient.Config(
                new HttpClient.Config(10, 5, TimeUnit.MINUTES)
                        .setTimeout(10 * 1000, 30 * 1000, 30 * 1000)
                        .setExecutorService(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2))));
    }

    /**
     * 本地Bucket相关API的签名器（账号在ucloud 的API 公私钥，不能使用token）
     * 如果只用到了文件操作，不需要配置下面的bucket 操作公私钥
     */
    public static final BucketAuthorization BUCKET_AUTHORIZER = new UfileBucketLocalAuthorization(
            PUBLIC_KEY,
            PRIVATE_KEY);

    /**
     * 本地Object相关API的签名器
     * 请修改下面的公私钥
     */
    public static final ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
            PUBLIC_KEY,
            PRIVATE_KEY);

    /**
     * 上传文件
     * @param file
     * @fileDirArray 文件目录集合，多个目录，会自动拼接
     * @return 真实文件访问路径
     */
    public static ResultCode uploadFile(File file, String...fileDirArray) {
        try {
            String extension = FilenameUtils.getExtension(file.getName());
            String fileDirName = null;
            if(fileDirArray != null){
                StringBuilder sbDir = new StringBuilder();
                for(String dir : fileDirArray) {
                    sbDir.append("/").append(dir);
                }
                fileDirName = sbDir.toString().replaceFirst("\\/","");
            }
            String filePath = ROOT_DIR+"/"+ (StringUtils.isNotBlank(fileDirName)?fileDirName+"/":"")+ DateUtil.format(new Date(),DateUtil.PATTERN_YYYYMMDD)+"/"+ RandomStringUtils.randomAlphabetic(16)+"."+extension;
            String mimeType = MimeTypeUtil.getMimeType(file);
            String fileUrl = "/" +filePath;
            PutObjectResultBean response = UfileClient.object(OBJECT_AUTHORIZER, config)
                    .putObject(file, mimeType)
                    .nameAs(filePath)
                    .toBucket(BUCKET)
                    /**
                     * 配置文件存储类型，分别是标准、低频、冷存，对应有效值：STANDARD | IA | ARCHIVE
                     */
                    .withStorageType(StorageType.STANDARD)
                    .execute();
            if(response.getRetCode() == 0){
                return ResultCode.getSuccessReturn(fileUrl);
            }
            return ResultCode.getFailure("上传文件失败，原因："+response.getMessage());
        } catch (UfileClientException e) {
            e.printStackTrace();
        } catch (UfileServerException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return ResultCode.getFailure("上传文件失败");
    }

    public static void main(String[] args) {
        File file = new File("D:\\b.jpg");
        ResultCode resultCode = uploadFile(file,"movie");
        System.out.println(FastJsonUtil.toJsonString(resultCode));
    }
}
